package dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import beans.Agent;

import utils.HibernateUtil;




public class AgentDao {
	private SessionFactory sessionFactory;

	public AgentDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	Transaction tr = null;
	
	/**
	 * 删除代理商
	 */
	public void delete(Agent agent) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.delete(agent);
		tr.commit();
		session.close();
	}
	
	/**
	 * 修改代理商
	 */
	public void edit(Agent agent) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(agent);
		tr.commit();
		session.close();
	}
	
	/**
	 * 保存新增的代理商
	 */
	public void save(Agent agent) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.save(agent);
		tr.commit();
		session.close();
	}
	
	/**
	 * 返回所有代理商信息
	 */
	public List<Agent> getAllAgent(){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Agent.class);
		List<Agent> agents=c.list();
		tr.commit();
		session.close();
		return agents;
	}
	/**
	 * 获取子代理商
	 * @return
	 */
	public List<Agent> getChildAgent(Agent agent){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Agent.class);
		c.add(Restrictions.eq("parentID", agent.getId()));
		List<Agent> agents=c.list();
		tr.commit();
		session.close();
		return agents;
	}
	
	/**
	 * 根据省城市返回所有代理商信息
	 */
	public List<Agent> getAgentByCity(String city){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Agent.class);
		c.add(Restrictions.eq("city", city));
		List<Agent> agents=c.list();
		tr.commit();
		session.close();
		return agents;
	}
	
	public List<Agent> getChildAndParentAgent(int agentId){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Agent.class);
//		c.add(Restrictions.eq("id", agentId));
//		c.add(Restrictions.disjunction().add(Restrictions.eq("parentID", agentId)));
//		c.add(Restrictions.eq("parentID", agentId));
		c.add(Restrictions.or(Restrictions.eq("id", agentId),Restrictions.eq("parentID", agentId)));
		List<Agent> agents=c.list();
		tr.commit();
		session.close();
		return agents;
	}

	/**
	 * 通过代理商ID返回指定代理商信息
	 * 
	 * @return
	 */
	public Agent getAgentById(int agentId) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Agent agent = (Agent) session.get(Agent.class, agentId);
		tr.commit();
		session.close();
		return agent;
	}
}
